package com.ws.base.common.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.ws.base.exception.WSException;

public final class FileUtil {
    private final int BUFFSIZE = 1024;

    /**
     * copyFile
     * 
     * @param inputStream
     * @param outFile
     *            void
     */
    public void copyFile(FileInputStream inputStream, File outFile) {
        OutputStream outputStream = null;
        byte[] tb = new byte[BUFFSIZE];
        int index = -1;

        try {
            outputStream = new FileOutputStream(outFile);

            while ((index = inputStream.read(tb)) != -1) {
                outputStream.write(tb, 0, index);
            }
        } catch (IOException e) {
            new WSException("Failed to copy files", e);
        } finally {
            FileUtil.close(outputStream);
            FileUtil.close(inputStream);
        }
    }

    /**
     * copyFile
     * 
     * @param inFile
     * @param outFile
     *            void
     */
    public void copyFile(File inFile, File outFile) {
        FileInputStream inputStream = null;

        try {
            inputStream = new FileInputStream(inFile);
        } catch (FileNotFoundException e) {
            new WSException("The target file does not exist", e);
        }
        this.copyFile(inputStream, outFile);
    }

    /**
     * close
     * 
     * @param closeable
     *            void
     */
    public static void close(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                new WSException("Close stream failed", e);
            }
        }
    }
}
